﻿using System;
using PMS.SANY.Entity;
using PMS.SANY.IBusiness;
using PMS.SANY.Models;
using PMS.SANY.Util;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using PMS.SANY.Api.Models;
using Microsoft.EntityFrameworkCore;
using System.Text;
using System.Net;
using System.IO;
using System.Text.Json.Serialization;

namespace PMS.SANY.Api.Controllers
{
    /// <summary>
    /// MaterielSortingConfig
    /// </summary>
    public class MaterielSortingConfigController : BaseController
    {
        /// <summary>
        /// 
        /// </summary>
        public IMaterielSortingConfigBusiness Bus { get; set; }

        /// <summary>
        /// Issued
        /// </summary>
        public IMaterielSortingIssuedBusiness IssuedBus { set; get; }

        /// <summary>
        /// 
        /// </summary>
        public IMaterielSortingLocationBusiness LocationBus { set; get; }

        /// <summary>
        /// 
        /// </summary>
        public IMaterielSortingSequenceBusiness SequenceBus { set; get; }

        /// <summary>
        /// 
        /// </summary>
        public IServiceProvider SvcProvider { get; set; }

        /// <summary>
        /// 通道编码
        /// </summary>
        private string ChannelCode { get { return "S7Net"; } }

        /// <summary>
        /// 设备编码
        /// </summary>
        private string DeviceCode { get { return "LLHCQ"; } }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="bus"></param>
        /// <param name="svcProvider"></param>
        /// <param name="issuedBus"></param>
        /// <param name="locationBus"></param>
        /// <param name="sequenceBus"></param>
        public MaterielSortingConfigController(IMaterielSortingConfigBusiness bus, IServiceProvider svcProvider
            , IMaterielSortingIssuedBusiness issuedBus
            , IMaterielSortingLocationBusiness locationBus
            , IMaterielSortingSequenceBusiness sequenceBus)
        {
            this.Bus = bus;
            this.IssuedBus = issuedBus;
            this.LocationBus = locationBus;
            this.SequenceBus = sequenceBus;

            this.SvcProvider = svcProvider;
        }

        /// <summary>
        /// 获取单个实体
        /// </summary>
        /// <param name="id">主键</param>
        /// <returns></returns>
        [HttpGet]
        public Task<MaterielSortingConfig> GetAsync(string id)
        {
            return this.Bus.GetAsync(id, true);
        }

        /// <summary>
        /// 获取分页数据
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpPost]
        public Task<PageResult<MaterielSortingConfig>> GetPageAsync(PageInput<MaterielSortingConfigQM> query)
        {
            return this.Bus.GetPageResultAsync(query);
        }

        /// <summary>
        /// 保存数据
        /// </summary>
        /// <param name="data">对应数据</param>
        /// <returns></returns>
        [HttpPost]
        [Transaction]
        public Task<int> SaveAsync(MaterielSortingConfig data)
        {
            this.InitBusEntity(data);
            return this.Bus.AddOrUpdateAsync(data);
        }

        /// <summary>
        /// 批量删除数据
        /// </summary>
        /// <param name="ids">数据主键</param>
        /// <returns></returns>
        [HttpDelete]
        [Transaction]
        public Task<int> DeleteAsync(List<string> ids)
        {
            return this.Bus.DeleteAsync(ids);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<string> SendAsync(string id)
        {
            WriteModel model = new WriteModel();
            string preAddress = string.Format("{0}.{1}", ChannelCode, DeviceCode);
            var config = this.Bus.GetAsync(id).Result;
            
            var queryable = this.LocationBus.GetQueryable(true);
            queryable = queryable.Include(i => i.Spec);
            var locations = queryable.Where(p => p.SortingConfigId == id).ToList();

            var queryable2 = this.SequenceBus.GetQueryable(true);
            queryable2 = queryable2.Include(i => i.SortingLocation).ThenInclude(i => i.Location);
            var sequences= queryable2.Where(p => p.SortingConfigId == id).ToList();

            var issueds = this.IssuedBus.GetListAsync(p => p.SortingConfigId == id).Result;

            model.Variables = new List<VariableModel>();
            model.Variables.Add(new VariableModel() { LogicAddress = string.Format("{0}.{1}", preAddress, config.CarNameAddress), Value = config.Name });
            model.Variables.Add(new VariableModel() { LogicAddress = string.Format("{0}.{1}", preAddress, config.VaneGrabCountAddress), Value = config.VaneGrabCount.ToString() });

            foreach (var loc in locations)
            {
                model.Variables.Add(new VariableModel() { LogicAddress = string.Format("{0}.{1}", preAddress, loc.CollectorAddress), Value = loc.Spec.Name });
            }

            foreach(var issued in issueds)
            {
                var locEleCode = (from u in sequences where u.SortingLocation.Location.ElectricCode == issued.SequenceIndex select u.SortingLocation.Location.ElectricCode).FirstOrDefault();
                if(locEleCode>0)
                {
                    model.Variables.Add(new VariableModel() { LogicAddress = string.Format("{0}.{1}", preAddress, issued.CollectorAddress), Value = locEleCode.ToString() });
                }
                else
                {
                    model.Variables.Add(new VariableModel() { LogicAddress = string.Format("{0}.{1}", preAddress, issued.CollectorAddress), Value = "0" });
                }
            }
          
            var message = PostHttpDataAsync("http://localhost:5000/Home/VariableWrite", Newtonsoft.Json.JsonConvert.SerializeObject(model));
            return message;
        }

        #region HTTP请求方法 
        /// <summary>
        /// 提交Http Post请求
        /// </summary>
        /// <param name="url"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        private async Task<string> PostHttpDataAsync(string url, string data)
        {
            try
            {
                byte[] dataArray = Encoding.Default.GetBytes(data);
                HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
                request.Method = "post";
                //request.ContentType = "application/x-www-form-urlencoded";
                request.ContentType = "application/json";
                //request.ContentType = "text/html";
                request.ContentLength = dataArray.Length;

                Stream dataStream = null;
                try
                {
                    dataStream = await request.GetRequestStreamAsync();
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }

                //发送请求
                dataStream.Write(dataArray, 0, dataArray.Length);
                dataStream.Close();

                // Get response
                using (var hwr = await request.GetResponseAsync())
                {
                    var response = hwr as HttpWebResponse;
                    StreamReader reader = new StreamReader(response.GetResponseStream());

                    return await reader.ReadToEndAsync();
                }
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public Task<int> ModifyGrabCountAsync(string id)
        {
            return this.Bus.ModifyGrabCountAsync(id);
        }
    }
}
